package org.jdns.jfreechess.draw;

import org.jdesktop.swingx.JXErrorPane;
import org.jdesktop.swingx.error.ErrorInfo;
import org.jdns.jfreechess.ics.IcsMessage;
import org.jdns.jfreechess.ics.IcsMessageHandler;

import java.awt.BorderLayout;
import java.awt.Font;
import java.awt.event.ActionEvent;
import java.io.BufferedWriter;
import java.io.IOException;
import java.io.OutputStream;
import java.io.OutputStreamWriter;
import java.util.logging.Level;

import javax.swing.AbstractAction;
import javax.swing.Action;
import javax.swing.JPanel;
import javax.swing.JScrollPane;
import javax.swing.JTextArea;
import javax.swing.JTextField;
import javax.swing.SwingUtilities;

/**
 * Reads an input stream line-by-line, renders it in a JTextArea. User input is read from a
 * JTextField and sent to an output stream when the user hits "Enter".
 *
 * @author James Ring (sjr@jdns.org)
 */
public class JConsole extends JPanel implements IcsMessageHandler {

  private final JTextArea consoleArea = new JTextArea(24, 80);
  private final JTextField inputField = new JTextField(80);
  private final BufferedWriter output;

  private final Action sendTextAction = new AbstractAction("Send") {
    @Override
    public void actionPerformed(ActionEvent e) {
      try {
        output.write(inputField.getText());
        output.flush();
      } catch (IOException ex) {
        JXErrorPane.showDialog(JConsole.this,
            new ErrorInfo("Error during send", "Oops", ex.getMessage(), "Input/Output", ex,
                Level.SEVERE, null));
      }
      inputField.setText("");
    }
  };

  public JConsole(OutputStream outputStream) {
    consoleArea.setFont(Font.getFont("Monospace"));

    setLayout(new BorderLayout());
    add(new JScrollPane(consoleArea), BorderLayout.CENTER);
    add(inputField, BorderLayout.SOUTH);

    output = new BufferedWriter(new OutputStreamWriter(outputStream));
    inputField.setAction(sendTextAction);
  }

  @Override
  public void messageReceived(final IcsMessage message) {
    SwingUtilities.invokeLater(new Runnable() {
      @Override
      public void run() {
        consoleArea.append(message.getContent());
      }
    });
  }
}
